package com.example.demo.controller;

import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.util.NamedList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

/**
 * @author xiah
 * @date 2018/5/25 11:03
 */
@RestController
@RequestMapping("/solr")
public class SolrController {
       @Autowired
       private SolrClient solrClient;

       @RequestMapping("/getSolr")
       public SolrDocumentList getSolr(@RequestParam String search) throws Exception {
              SolrQuery solrQuery = new SolrQuery(search);
              /*开启分面功能*/
              //solrQuery.setFacet(true);
              /*设置分面值返回的条数*/
              //solrQuery.setFacetLimit(100);
              /*设置分面字段，多个字段以逗号分割*/
              //solrQuery.setFields("");
              solrQuery.setHighlight(true);//开启高亮
              solrQuery.addHighlightField("name");
              //设置前缀
              solrQuery.setHighlightSimplePre("<span style='color:red'>");
              //设置后缀
              solrQuery.setHighlightSimplePost("</span>");
              QueryResponse queryResponse = solrClient.query(solrQuery);
           /*   SolrDocument solrDocument = solrClient.getById("SOLR1000xiah");
              Object object = solrDocument.getFieldValue("features");*/
              System.out.println(queryResponse);
              String ss = queryResponse.getRequestUrl();
              Map<String, Map<String, List<String>>> map = queryResponse.getHighlighting();
              Map<String, List<String>> mm = map.get("1");
              List<String> list3 = mm.get("name");
              NamedList list = queryResponse.getResponse();
              Object ll = list.get("response");
              NamedList list2 = queryResponse.getResponseHeader();
              SolrDocumentList solrDocumentList = queryResponse.getResults();
              return solrDocumentList;
       }

       @RequestMapping("/addSolr")
       public Object addSolr() throws Exception {
              SolrInputDocument solrInputFields = new SolrInputDocument();
              solrInputFields.addField("id", "1");
              solrInputFields.addField("name", "我是谁在哪里333");
              solrInputFields.addField("content", "一生襟抱未曾开");
              solrClient.add(solrInputFields);
              solrClient.commit();
              return "ok";
       }

}
